package com.lock.zklock;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.concurrent.TimeUnit;

public class Test_ZkLock {

    public static void main(String[] args) throws InterruptedException {
        ApplicationContext app = new ClassPathXmlApplicationContext("spring-context.xml");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("1111111111111");
                    boolean b = ZkLockHelper.getInstance().getLock("testLocak", 1, TimeUnit.SECONDS);
                    if (b) {
                        System.out.println("线程1获得锁：" + System.currentTimeMillis());
                    } else {
                        System.out.println("线程1未获得锁：" + System.currentTimeMillis());
                    }
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    ZkLockHelper.getInstance().releaseLock("testLocak");
                }
            }
        }).start();
        Thread.sleep(2000);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("2222222222222222");
                    //
                    boolean b = ZkLockHelper.getInstance().getLock("testLocak", 0, TimeUnit.MILLISECONDS);
                    if (b) {
                        System.out.println("线程2获得锁：" + System.currentTimeMillis());
                    } else {
                        System.out.println("线程2未获得锁：" + System.currentTimeMillis());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    ZkLockHelper.getInstance().releaseLock("testLocak");
                }
            }
        }).start();
    }
}
